package org.xiangfei.server.handler;

import java.util.Date;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.xiangfei.codec.bean.XFMessage;
import org.xiangfei.server.logic.UserChannelService;
import org.xiangfei.server.logic.UserService;


/** 
* @author feesx@qq.com
* @version 2017年7月6日 下午9:53:15 
* 类说明 
*/
@Sharable
public class XFServerHandler extends SimpleChannelInboundHandler<XFMessage> {
    // 总共多少个channel,一个群可以当作一个channelgroup
    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    // usertoken 对应的channel
   
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        // Broadcast a message to multiple Channels
        channels.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 加入\n");
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 
        Channel incoming = ctx.channel();
        // Broadcast a message to multiple Channels
        channels.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
        // A closed Channel is automatically removed from ChannelGroup,
        // so there is no need to do "channels.remove(ctx.channel());"
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, XFMessage sendMessage) throws Exception {
        // 判断自己的channel是否存在，如果不存在则新增
        if (UserChannelService.getChannel(sendMessage.getSendUserId()) == null) {
            UserChannelService.setChannel(sendMessage.getSendUserId(), ctx.channel());
        }
        // 判断好友的channel是否存在
        if (UserChannelService.getChannel(sendMessage.getReceiveUserId()) != null) {
            System.out.println(sendMessage.getSendUserId() + "发送给" + sendMessage.getReceiveUserId() 
            + "，内容是：" + sendMessage.getMessage());

            UserChannelService.getChannel(sendMessage.getReceiveUserId()).writeAndFlush(sendMessage);
        } else {
            //TODO 如果好友channel不存在，则把消息丢到队列 
            System.out.println(sendMessage.getReceiveUserId() + "离线，消息进入队列");
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient: 客户端激活" + incoming.remoteAddress() + "在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient: 客户端掉线" + incoming.remoteAddress() + "掉线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient: 客户端异常" + incoming.remoteAddress() + "异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
   
}
 
